package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.service.ISmsService;
import com.eco.fanliapp.utils.AliYunMesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements ISmsService {
    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);
    @Autowired
    private RedisTemplate redisTemplate;

    /*@Override
    public String sendSms(String phone) {
        boolean hasKey =   redisTemplate.hasKey(phone);
        if(hasKey){
            return  (String)redisTemplate.opsForValue().get(phone);
        }
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
        final String accessKeyId = ApiEnum.ACCESSKEYID;
        final String accessKeySecret = ApiEnum.ACCESSKEYSECRET;//你的accessKeySecret，
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(phone);
        request.setSignName(ApiEnum.SIGNNAME);
        request.setTemplateCode(ApiEnum.TEMPLATECODE);
        String code =  getCode();
        request.setTemplateParam("{\"code\":\""+code+"\"}");
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            //5分钟失效
            redisTemplate.opsForValue().set(phone, code, 60 * 5, TimeUnit.SECONDS);
            return code;
        } else {
            return null;
        }
    }*/

    public static   String getCode(){
        String sources = "0123456789"; // 加上一些字母，就可以生成pc站的验证码了
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 4; j++)
        {
            flag.append(sources.charAt(rand.nextInt(9)) + "");
        }
        return flag.toString();
    }

    @Override
    public String sendSms(String phone) {
        //参数
        String signName = ApiEnum.SIGNNAME;
        String templateCode = ApiEnum.SMS_TEMPLATE1;
        String code = getCode();
        String templateParam = "{\"code\":\"" + code + "\"}";

        //防止暴力刷新
        boolean hasKey =   redisTemplate.hasKey(phone);
        if(hasKey){
            return  (String)redisTemplate.opsForValue().get(phone);
        }
        //发送短信
        log.info("登陆校验参数：accessKeyId:{},accessKeySecret:{},phone:{},signName:{},templateCode:{},content:{}",phone,signName,templateCode,templateParam);
        JSONObject jsonObject = AliYunMesUtils.SendSms( phone, signName, templateCode, templateParam);
        log.info("短信发送结果：{}",jsonObject.toJSONString());
        //结果校验
        if (jsonObject != null && "OK".equals(jsonObject.getString("Code"))) {
            //5分钟失效
            redisTemplate.opsForValue().set(phone, code, 60 * 5, TimeUnit.SECONDS);
            return code;
        } else {
            return null;
        }
    }

    @Override
    public String sendSms2(String phone, String ip, String serverName, String port) {
        //参数
        String signName = ApiEnum.SIGNNAME;
        String templateCode = ApiEnum.SMS_TEMPLATE2;
        //String templateParam = "{\"serverName\":\"" + serverName + "\"}";
        String templateParam = "{\"ip\":\"" + ip + "\",\"serverName\":\"" + serverName + "\",\"port\":\"" + port + "\"}";
        //防止暴力刷新
        boolean hasKey =   redisTemplate.hasKey(phone);
        if(hasKey){
            return  (String)redisTemplate.opsForValue().get(phone);
        }
        //发送短信
        log.info("登陆校验参数：accessKeyId:{},accessKeySecret:{},phone:{},signName:{},templateCode:{},content:{}",phone,signName,templateCode,templateParam);
        JSONObject jsonObject = AliYunMesUtils.SendSms( phone, signName, templateCode, templateParam);
        log.info("短信发送结果：{}",jsonObject.toJSONString());
        //结果校验
        if (jsonObject != null && "OK".equals(jsonObject.getString("Code"))) {
            //5分钟失效
            redisTemplate.opsForValue().set(phone, "异常提示成功", 60 * 5, TimeUnit.SECONDS);
            return "服务异常短信提示短信发送成功";
        } else {
            return "服务异常提示短信发送失败";
        }
    }

    @Override
    public String sendSms3(String phone,String time) {

        //参数
        String signName = ApiEnum.SIGNNAME;
        String templateCode = ApiEnum.SMS_TEMPLATE3;
        String templateParam = "{\"time\":\"" + time + "\"}";

        //防止暴力刷新
        boolean hasKey =   redisTemplate.hasKey(phone);
        if(hasKey){
            return  (String)redisTemplate.opsForValue().get(phone);
        }
        //发送短信
        log.info("登陆校验参数：accessKeyId:{},accessKeySecret:{},phone:{},signName:{},templateCode:{},content:{}",phone,signName,templateCode,templateParam);
        JSONObject jsonObject = AliYunMesUtils.SendSms( phone, signName, templateCode, templateParam);
        log.info("短信发送结果：{}",jsonObject.toJSONString());
        //结果校验
        if (jsonObject != null && "OK".equals(jsonObject.getString("Code"))) {
            //5分钟失效
            redisTemplate.opsForValue().set(phone, "异常提示成功", 60 * 5, TimeUnit.SECONDS);
            return "异常提示短信发送成功";
        } else {
            return "异常提示短信发送失败";
        }
    }

    @Override
    public String sendSms4(String phone, String name) {
        //参数
        String signName = ApiEnum.SIGNNAME;
        String templateCode = ApiEnum.SMS_TEMPLATE4;
        String templateParam = "{\"name\":\"" + name + "\"}";

        //防止暴力刷新
        boolean hasKey =   redisTemplate.hasKey(phone);
        if(hasKey){
            return  (String)redisTemplate.opsForValue().get(phone);
        }
        //发送短信
        log.info("登陆校验参数：accessKeyId:{},accessKeySecret:{},phone:{},signName:{},templateCode:{},content:{}",phone,signName,templateCode,templateParam);
        JSONObject jsonObject = AliYunMesUtils.SendSms( phone, signName, templateCode, templateParam);
        log.info("短信发送结果：{}",jsonObject.toJSONString());
        //结果校验
        if (jsonObject != null && "OK".equals(jsonObject.getString("Code"))) {
            //5分钟失效
            redisTemplate.opsForValue().set(phone, "异常提示成功", 60 * 5, TimeUnit.SECONDS);
            return "联盟到期短信提示短信发送成功";
        } else {
            return "联盟到期提示短信发送失败";
        }
    }

    @Override
    public String sendSms5(String phone, String content) {
        //参数
        String signName = ApiEnum.SIGNNAME;
        String templateCode = ApiEnum.SMS_TEMPLATE5;
        String templateParam = "{\"content\":\"" + content + "\"}";

        //防止暴力刷新
        boolean hasKey =   redisTemplate.hasKey(phone);
        if(hasKey){
            return  (String)redisTemplate.opsForValue().get(phone);
        }
        //发送短信
        log.info("登陆校验参数：accessKeyId:{},accessKeySecret:{},phone:{},signName:{},templateCode:{},content:{}",phone,signName,templateCode,templateParam);
        JSONObject jsonObject = AliYunMesUtils.SendSms( phone, signName, templateCode, templateParam);
        log.info("短信发送结果：{}",jsonObject.toJSONString());
        //结果校验
        if (jsonObject != null && "OK".equals(jsonObject.getString("Code"))) {
            //5分钟失效
            redisTemplate.opsForValue().set(phone, "异常提示成功", 60 * 5, TimeUnit.SECONDS);
            return "红包领取短信提示短信发送成功";
        } else {
            return "红包领取提示短信发送失败";
        }
    }
}
